<script setup>
import { ref, onMounted } from 'vue'
import courseService from '../../services/course'
import { showError } from '../../utils/message'

const props = defineProps({
  student: {
    type: Object,
    required: true
  }
})

const dialogVisible = ref(false)
const loading = ref(false)
const courses = ref([])

// 打开对话框
const openDialog = async () => {
  dialogVisible.value = true
  await loadStudentCourses()
}

// 加载学生课程
const loadStudentCourses = async () => {
  try {
    loading.value = true
    courses.value = await courseService.getStudentCourses(props.student.id)
  } catch (error) {
    showError('加载课程数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  courses.value = []
}

defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="student ? `${student.name}的课程列表` : '课程列表'"
    width="800px"
    @close="handleClose"
  >
    <div class="course-view-dialog">
      <el-table
        v-loading="loading"
        :data="courses"
        style="width: 100%"
      >
        <el-table-column prop="name" label="课程名称" />
        <el-table-column prop="description" label="课程描述" />
        <el-table-column prop="duration" label="课程时长" width="100">
          <template #default="{ row }">
            {{ row.duration }}小时
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100" />
        <el-table-column prop="level" label="难度" width="100">
          <template #default="{ row }">
            <el-tag :type="row.level === '初级' ? 'success' : row.level === '中级' ? 'warning' : 'danger'">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.course-view-dialog {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
